package com.example.ordermealservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.commonutils.R;
import com.example.ordermealservice.client.OrdermealClient;
import com.example.ordermealservice.entity.OrderDish;
import com.example.ordermealservice.entity.OrderShoppingCart;
import com.example.ordermealservice.entity.vo.DishSelectByConditionVO;
import com.example.ordermealservice.service.OrderDishService;
import com.example.ordermealservice.service.OrderShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-06-13
 */
@RestController
@RequestMapping("/ordermealservice/orderdish")
public class OrderDishController {
    @Autowired
    private OrderDishService orderDishService;
    @Autowired
    private OrdermealClient ordermealClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OrderShoppingCartService orderShoppingCartService;
    //新增菜品
    @PostMapping("/createDish")
    public R createDish(@RequestBody OrderDish orderDish){
        orderDishService.save(orderDish);
        stringRedisTemplate.delete("cache:dishAmount");
        Set<String> keys = stringRedisTemplate.keys("cache:dishes" + "*");
        stringRedisTemplate.delete(keys);
        return R.ok().message("添加菜品成功！");
    }
    //回显菜品信息
    @GetMapping("/selectDish/{dishId}")
    public R selectDish(@PathVariable String dishId){
        OrderDish dish = orderDishService.getById(dishId);
        return R.ok().data("dish",dish);
    }
    //修改菜品信息
    @PostMapping("/editDish")
    public R editDish(@RequestBody OrderDish orderDish){
        //如果输入的价格小于0，则赋值为0
        if (orderDish.getDishPrice().compareTo(BigDecimal.ZERO) == -1){
            orderDish.setDishPrice(BigDecimal.ZERO);
        }
        //如果输入的库存数量小于0，则赋值为0
        if (orderDish.getDishNumber() < 0){
            orderDish.setDishNumber(0);
        }
        //如果修改后库存为0，自动下架
        if (orderDish.getDishNumber() == 0){
            orderDish.setDishStatus(0);
        }
        orderDishService.updateById(orderDish);
        stringRedisTemplate.delete("cache:dishAmount");
        Set<String> keys = stringRedisTemplate.keys("cache:dishes" + "*");
        stringRedisTemplate.delete(keys);
        return R.ok().message("菜品信息修改成功");
    }
    //带条件的分页查询(根据菜品名称、菜品分类、菜品状态等多条件进行查询)
    @PostMapping("/selectPageByCondition/{page}/{pageSize}")
    public R selectPageByCondition(@RequestBody DishSelectByConditionVO dishSelectByConditionVO,
                                   @PathVariable int page, @PathVariable int pageSize){
        LambdaQueryWrapper<OrderDish> queryWrapper = new LambdaQueryWrapper<>();
        String dishName = dishSelectByConditionVO.getDishName();
        String category = dishSelectByConditionVO.getCategory();
        String subCategory = dishSelectByConditionVO.getSubCategory();
        Integer dishStatus = dishSelectByConditionVO.getDishStatus();
        queryWrapper.like(null != dishName,OrderDish::getDishName,dishName);
        queryWrapper.eq(null != category,OrderDish::getDishClassification,category);
        queryWrapper.eq(null != subCategory,OrderDish::getDishSubclassification,subCategory);
        queryWrapper.eq(null != dishStatus,OrderDish::getDishStatus,dishStatus);
        queryWrapper.orderByDesc(OrderDish::getGmtCreate);
        Page<OrderDish> pageInfo = new Page<>(page,pageSize);
        orderDishService.page(pageInfo,queryWrapper);
        return R.ok().data("pageInfo",pageInfo);
    }
    @DeleteMapping("/deletedish")
    public R deleteDish(@RequestParam List<String> ids){
        if (ids.size()==0){
            return R.error().message("请选中需要删除的菜品");
        }
        LambdaQueryWrapper<OrderDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OrderDish::getId,ids);
        List<OrderDish> list = orderDishService.list(queryWrapper);
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String dishPicture = list.get(i).getDishPicture();
            // 第三个"/"后面的内容为图片名
            int index = dishPicture.indexOf("/");
            index = dishPicture.indexOf("/",index + 1);
            index = dishPicture.indexOf("/",index + 1);
            String fileName = dishPicture.substring(index + 1);
            arrayList.add(fileName);
        }
        orderDishService.batchDelete(ids);
//        删除成功后删除OSS中的图片
        // 服务的远程调用
        for (int i = 0; i < arrayList.size(); i++) {
            ordermealClient.deleteFile(arrayList.get(i));
        }
        stringRedisTemplate.delete("cache:dishAmount");
        Set<String> keys = stringRedisTemplate.keys("cache:dishes" + "*");
        stringRedisTemplate.delete(keys);
        return R.ok().message("删除成功");
    }
    // 修改菜品状态
    @PostMapping("/editStatus/{id}")
    public R editStatus(@PathVariable String id){
        LambdaQueryWrapper<OrderDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDish::getId,id);
        OrderDish orderDish = orderDishService.getOne(queryWrapper);
        Integer dishStatus = orderDish.getDishStatus();
        Integer dishNumber = orderDish.getDishNumber();
        if (dishStatus == 0){
            //如果此时的状态的已下架
            if (dishNumber > 0){
                //如果库存不为0，则上架
                orderDish.setDishStatus(1);
            }else {
                //如果库存为0
                return R.error().message("请添加库存后重试");
            }
        }else {
            orderDish.setDishStatus(0);
            // TODO 如果将菜品下架，购物车中的该菜品就应该被删除
            LambdaQueryWrapper<OrderShoppingCart> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderShoppingCart::getDishId,id);
            orderShoppingCartService.remove(queryWrapper1);

        }
        orderDishService.updateById(orderDish);
        stringRedisTemplate.delete("cache:dishAmount");
        Set<String> keys = stringRedisTemplate.keys("cache:dishes" + "*");
        stringRedisTemplate.delete(keys);
        return R.ok();
    }
    //根据dishId和dishNumber减库存
    @PutMapping("/subNumber/{dishId}/{dishNumber}")
    public R subNumber(@PathVariable String dishId, @PathVariable Integer dishNumber){
        R r = orderDishService.subNumber(dishId, dishNumber);
        if (r.getCode()==20001){
            return R.error();
        }
        stringRedisTemplate.delete("cache:dishAmount");
        Set<String> keys = stringRedisTemplate.keys("cache:dishes" + "*");
        stringRedisTemplate.delete(keys);
        return R.ok();
    }
    //根据dishId查询dishTime
    @GetMapping("/selectTime/{dishId}")
    public int selectTime(@PathVariable String dishId){
        OrderDish dish = orderDishService.getById(dishId);
        Integer dishTime = dish.getDishTime();
        return dishTime;
    }
}

